package com.gitee.chili.leisure.message;

import com.gitee.chili.leisure.RoomManager;
import com.gitee.chili.leisure.core.AbstractDefaultMessage;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.enums.CardType;
import com.gitee.chili.leisure.game.MahjongPlayer;
import com.gitee.chili.leisure.game.RoomDetail;
import com.gitee.chili.leisure.model.MahjongModel;
import com.gitee.chili.leisure.util.AuxiliaryRoom;
import com.gitee.chili.leisure.util.Enum;
import com.gitee.chili.leisure.util.TaskManager;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.channel.Channel;

/**
 * 定缺
 *
 * @author week solider
 * @since 2020.09.19
 */
public class Useless extends AbstractDefaultMessage {

    private boolean over = true;

    public Useless(Packet packet, Channel channel) {
        super(packet, channel);
    }

    @Override
    protected void decoder(byte[] body) throws InvalidProtocolBufferException {
        MahjongModel.UselessCmd useless = MahjongModel.UselessCmd.parseFrom(body);

        Long roomNum = getRoomNum();

        // 缓存定缺信息
        RoomDetail roomDetail = RoomManager.obtain(roomNum);

        MahjongPlayer player = (MahjongPlayer) roomDetail.obtain(getMemberId());
        player.setUseless(Enum.valueOf(CardType.class, u -> u.ordinal() == useless.getType()));

        // 任务名
        String name = String.format(TaskManager.TaskNames.multiUseless, roomNum.toString());

        // 移除个人定时任务
        TaskManager.remove(name, player.getUserId());

        // 检查所有牌友是否都已经定缺完毕
        over = AuxiliaryRoom.uselessOver(roomDetail.getPlayers());
    }

    @Override
    public Packet parseBody() {
        return AuxiliaryRoom.uselessFinish(RoomManager.obtain(getRoomNum()).getPlayers());
    }

    /**
     * 是否定缺结束
     */
    public boolean isOver() {
        return over;
    }
}
